package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /*
     * 用户登录/游客登录
     * */
    @Override
    public ResponseResult login(LoginDTO loginDTO) {
        //1.正常登录(用户名和密码都存在)
        //1.1.按照phone查询用户信息
        //1.2.用户信息不存在
        //1.3.用户存在
        //1.4.提交的密码加盐加密与用户密码比对
        //1.5.密码有误
        //1.6.密码正确
        //1.7.生成token,返回token和用户信息的集合map
        //2.游客登录
        //2.1 id=0,直接生成token
        //3.非正常登录(用户名或密码只有一个存在)

        if (StringUtils.isNotEmpty(loginDTO.getPhone()) && StringUtils.isNotEmpty(loginDTO.getPassword())) {

            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDTO.getPhone()));

            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            String inputPasswordWithSalt = DigestUtils.md5DigestAsHex((loginDTO.getPassword() + apUser.getSalt()).getBytes());

            if (!inputPasswordWithSalt.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            Map userMap = new HashMap();
            userMap.put("id", apUser.getId());
            userMap.put("name", apUser.getName());
            userMap.put("phone", apUser.getPhone());
            Map map = new HashMap();
            map.put("user", userMap);
            map.put("token", token);
            return ResponseResult.okResult(map);

        } else if (StringUtils.isEmpty(loginDTO.getPhone()) && StringUtils.isEmpty(loginDTO.getPassword())) {
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);

        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
    }
}